package org.wu.framework.inner.lazy.orm.spring.prop;

import org.wu.framework.lazy.orm.core.config.prop.AbstractLazyDataSourceAttribute;
import org.wu.framework.lazy.orm.core.config.prop.LazyDataSourceAttribute;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;

import javax.sql.DataSource;

/**
 * description 懒人数据源配置 (可选)
 * 默认使用 MysqlDataSource
 *
 * @author Jia wei Wu
 * @date 2021/4/23 下午1:39
 *
 * @see LazyDataSourceAttribute
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "spring.datasource", value = "url")
@ConfigurationProperties(prefix = "spring.datasource")
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class LazyDataSourceProperties extends AbstractLazyDataSourceAttribute {

    /**
     * Initialize a {@link DataSourceBuilder} with the state of this instance.
     *
     * @return a {@link DataSourceBuilder} initialized with the customizations defined on
     * this instance
     */
    public DataSourceBuilder<?> initializeDataSourceBuilder() {
        return DataSourceBuilder.create()
                .type(switchType())
                .driverClassName(switchDriverClassName())
                .url(getUrl())
                .username(getUsername())
                .password(getPassword());
    }


    /**
     * 获取数据源
     *
     * @return 数据源
     */
    @Override
    public DataSource doGetDatasource() {
        return initializeDataSourceBuilder().build();
    }
}
